package org.icy.core.parser;

import java.io.File;
import java.io.FileInputStream;

import org.ice.config.ConfigData;
import org.ice.config.DefaultConfigData;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class XMLParser {

	public ConfigData parse(File f) throws Exception {
		InputSource is = new InputSource(new FileInputStream(f));
		
		XMLReader parser = XMLReaderFactory.createXMLReader();
		ConfigData output = new DefaultConfigData();
		parser.setContentHandler(new ConfigContentHandler(output));
		parser.parse(is);
		return output;
	}
	
	class ConfigContentHandler extends DefaultHandler {
		
		private ConfigData output;
		private String currentName;
		private StringBuffer currentContent;
		
		public ConfigContentHandler(ConfigData output) {
			super();
			this.output = output;
		}
		
		public void startElement(String uri, String localName, String qName, Attributes attributes) {
			currentContent = new StringBuffer();
			currentName = localName;
		}
		
		public void characters(char[] ch, int start, int length) {
			currentContent.append(ch, start, length);
		}
		
		public void endElement(String uri, String localName, String qName) {
			output.set(currentName, currentContent.toString());
		}
	}
}
